package com.eazy.lkv2.web.support;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.eazy.lkv2.core.web.utils.Export;
import com.eazy.lkv2.core.web.utils.ExportExcel;
import com.eazy.lkv2.core.web.utils.ExportPdf;
import com.eazy.lkv2.core.web.utils.ExportWord;

/**
 * @author jzx
 * @date 2016.6.3
 * @desc baseController 工具类
 */
public final class ActionRequest {

	public static String getPara(String name, HttpServletRequest request) {
		return request.getParameter(name);
	}

	public static String getPara(String name, String defaultValue, HttpServletRequest request) {
		String result = request.getParameter(name);
		return result != null && !"".equals(result) ? result : defaultValue;
	}

	public static String[] getParaValues(String name, HttpServletRequest request) {
		return request.getParameterValues(name);
	}

	public static Object getAttr(HttpServletRequest request, String key) {
		return request.getAttribute(key);
	}

	public static Enumeration<String> getAttrs(HttpServletRequest request) {
		return request.getAttributeNames();
	}

	public static void setAttr(HttpServletRequest request, String key, Object value) {
		request.setAttribute(key, value);
	}

	public static void setAttrs(HttpServletRequest request, Map<String, Object> map) {
		for (Map.Entry<String, Object> m : map.entrySet()) {
			request.setAttribute(m.getKey(), m.getValue());
		}
	}

	public static void renderJson(String data, HttpServletResponse response) {
		try {
			response.setContentType("application/json;charset=utf-8");
			PrintWriter out = response.getWriter();
			out.write(data);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void renderWEP(String fileName, String columnName, List<String[]> list1, int importWEP,
			HttpServletResponse response) {
		try {
			response.reset();
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);// 指定下载的文件名
			response.setContentType("application/msexcel;charset=UTF-8");
			ServletOutputStream outputStream = response.getOutputStream();
			Export excel = null;
			if (importWEP == 1) {
				excel = new ExportWord();
			} else if (importWEP == 2) {
				excel = new ExportExcel();
			} else if (importWEP == 3) {
				excel = new ExportPdf();
			}
			OutputStream out = null;
			out = excel.writeStream(outputStream, columnName, list1);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
